﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.InvoiceAndReceiptManage;
using ProduceBasicData.Api.DTO.InvoiceAndReceiptDto;
using ProduceBasicData.Domain.InvoiceAndReceiptManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.InvoiceAndReceiptManage
{
    /// <summary>
    /// 获取开票信息
    /// </summary>
    public class GetInvoiceHandler : IRequestHandler<GetInvoiceCommand, ApiPaging<InvoiceDto>>
    {
        private readonly IBaseRespository<Invoice> _invoiceRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="invoiceRepository"></param>
        /// <param name="mapper"></param>
        public GetInvoiceHandler(IBaseRespository<Invoice> invoiceRepository, IMapper mapper)
        {
            _invoiceRepository = invoiceRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<InvoiceDto>> Handle(GetInvoiceCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<InvoiceDto>();

            try
            {
                // 获取基础查询（排除已删除的数据）
                var invoice = await _invoiceRepository.GetAllAsync();
                var query = invoice.Where(x => x.Isdel == false);

                // 应用查询条件（如果有）
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    query = query.Where(x =>
                        x.SystemNo != null && x.SystemNo.Contains(request.Keyword));
                }

                // 获取总记录数
                result.TotalCount = query.Count();

                // 执行分页查询
                if (result.TotalCount > 0)
                {
                    // 应用分页
                    var pagedData = query.OrderByDescending(x => x.CreateTime)
                        .Skip((request.Index - 1) * request.Size)
                        .Take(request.Size)
                        .ToList();

                    // 映射到DTO
                    result.PageDatas = pagedData.Select(x => new InvoiceDto
                    {
                        Id = x.Id,
                        SystemNo = x.SystemNo,
                        InvoiceSubject = x.InvoiceSubject,
                        InvoiceType = x.InvoiceType,
                        InvoiceDate = x.InvoiceDate,
                        IsBindSalesOrder = x.IsBindSalesOrder,
                        Payee = x.Payee,
                        InvoiceNo = x.InvoiceNo,
                        SalesOrderNo = x.SalesOrderNo,
                        SalesOrderSubject = x.SalesOrderSubject,
                        Amount = x.Amount,
                        Attachment = x.Attachment,
                        OutboundStatus = x.OutboundStatus,
                        Status = x.Status,
                        CreateName = x.CreateName,
                        CreateTime = x.CreateTime,
                        UpdateName = x.UpdateName,
                        UpdateTime = x.UpdateTime,
                        Isdel = x.Isdel
                    }).ToList();
                }
                else
                {
                    result.PageDatas = new List<InvoiceDto>();
                }

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                // 记录日志（实际项目中应使用专门的日志组件）
                // logger.LogError(ex, "开票查询异常");

                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.PageDatas = new List<InvoiceDto>();
            }

            return result;
        }
    }
}
